package com.gemcoder.system.service;

import static com.gemcoder.system.datasource.JdbcTemplateUtil.executeSQL;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserName;
import static com.gemcoder.system.service.UserSdkService.sdkOfGetCurrentUserId;
import com.gemcoder.system.bo.Result;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllPermissions;
import static com.gemcoder.system.service.permission.PermissionSdkService.sdkOfgetAllMenus;
import java.sql.SQLException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import cn.hutool.core.util.StrUtil;
import java.time.LocalDateTime;
import cn.hutool.db.sql.SqlBuilder;

@Service
public class AlarmrulesService {

    public Result getAllProjects(Map<String, Object> paramMap) {
        // 构建查询所有项目的SQL
        StringBuilder sql = new StringBuilder("SELECT id, project_name, water_source, project_location, billing_method, start_date, project_status, project_score, operation_manager, contact_info, create_time, update_time, create_username, update_username FROM project");
        // 执行SQL查询
        List<Map<String, Object>> result = executeSQL(sql.toString());
        // 构建返回结果
        Result res = new Result();
        res.setFlag(true);
        res.setMessage("查询成功");
        res.setData(result);
        return res;
    }

    public Result getDeviceMetrics(Map<String, Object> paramMap) {
        // 从paramMap中获取设备名称
        String deviceName = paramMap.get("deviceName") != null ? String.valueOf(paramMap.get("deviceName")) : null;
        // 检查设备名称是否为空
        if (deviceName == null) {
            return new Result(false, "设备名称不能为空", null);
        }
        // 构建查询设备指标的SQL
        StringBuilder sql = new StringBuilder("SELECT device_metric FROM alarm_rules WHERE device_name = ?");
        List<Object> params = new ArrayList<>();
        params.add(deviceName);
        // 执行SQL查询
        List<Map<String, Object>> result = executeSQL(sql.toString(), params.toArray());
        // 返回结果
        return new Result(true, "查询成功", result);
    }

    public Result getAlarmRules(Map<String, Object> paramMap) {
        String projectName = paramMap.get("ProjectNamevalue1") != null ? String.valueOf(paramMap.get("ProjectNamevalue1")) : null;
        String deviceMetric = paramMap.get("Equipmentindexvalue2") != null ? String.valueOf(paramMap.get("Equipmentindexvalue2")) : null;
        Integer current = paramMap.get("current") != null ? Integer.valueOf(String.valueOf(paramMap.get("current"))) : 1;
        Integer pageSize = paramMap.get("pageSize") != null ? Integer.valueOf(String.valueOf(paramMap.get("pageSize"))) : 10;
        StringBuilder sql = new StringBuilder("SELECT id, timestamp, project_name, device_name, device_metric, operator, target_value, unit, category, display_content, creator, time_metric, time_reference_value FROM alarm_rules WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (projectName != null) {
            sql.append(" AND project_name = ?");
            params.add(projectName);
        }
        if (deviceMetric != null) {
            sql.append(" AND device_metric = ?");
            params.add(deviceMetric);
        }
        // Pagination
        int offset = (current - 1) * pageSize;
        sql.append(" LIMIT ?, ?");
        params.add(offset);
        params.add(pageSize);
        List<Map<String, Object>> data = executeSQL(sql.toString(), params.toArray());
        // Count total
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) as total FROM alarm_rules WHERE 1=1");
        List<Object> countParams = new ArrayList<>();
        if (projectName != null) {
            countSql.append(" AND project_name = ?");
            countParams.add(projectName);
        }
        if (deviceMetric != null) {
            countSql.append(" AND device_metric = ?");
            countParams.add(deviceMetric);
        }
        List<Map<String, Object>> countResult = executeSQL(countSql.toString(), countParams.toArray());
        int total = countResult.get(0).get("total") != null ? Integer.valueOf(String.valueOf(countResult.get(0).get("total"))) : 0;
        Result result = new Result();
        result.setFlag(true);
        result.setMessage("Query successful");
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("total", total);
        resultData.put("data", data);
        result.setData(resultData);
        return result;
    }

    public Result addAlarmRule(Map<String, Object> paramMap) {
        String timestamp = paramMap.get("Timevalue1") != null ? String.valueOf(paramMap.get("Timevalue1")) : null;
        String projectName = paramMap.get("ProjectName1value1") != null ? String.valueOf(paramMap.get("ProjectName1value1")) : null;
        String deviceName = paramMap.get("EquipmentNamevalue1") != null ? String.valueOf(paramMap.get("EquipmentNamevalue1")) : null;
        String deviceMetric = paramMap.get("Equipmentindexvalue1") != null ? String.valueOf(paramMap.get("Equipmentindexvalue1")) : null;
        String operator = paramMap.get("Operatorvalue1") != null ? String.valueOf(paramMap.get("Operatorvalue1")) : null;
        String targetValue = paramMap.get("TargetValuevalue1") != null ? String.valueOf(paramMap.get("TargetValuevalue1")) : null;
        String unit = paramMap.get("Unitvalue1") != null ? String.valueOf(paramMap.get("Unitvalue1")) : null;
        String category = paramMap.get("Alarmcategoryvalue1") != null ? String.valueOf(paramMap.get("Alarmcategoryvalue1")) : null;
        String displayContent = paramMap.get("Displaycontentsvalue1") != null ? String.valueOf(paramMap.get("Displaycontentsvalue1")) : null;
        String timeMetric = paramMap.get("TimeIndexvalue1") != null ? String.valueOf(paramMap.get("TimeIndexvalue1")) : null;
        String creator = sdkOfGetCurrentUserName();
        String timeReferenceValue = paramMap.get("Timereferencevaluevalue1") != null ? String.valueOf(paramMap.get("Timereferencevaluevalue1")) : null;
        StringBuilder sql = new StringBuilder("INSERT INTO alarm_rules (timestamp, project_name, device_name, device_metric, operator, target_value, unit, category, display_content, creator, time_metric, time_reference_value, create_username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        List<Object> params = new ArrayList<>();
        params.add(timestamp);
        params.add(projectName);
        params.add(deviceName);
        params.add(deviceMetric);
        params.add(operator);
        params.add(targetValue);
        params.add(unit);
        params.add(category);
        params.add(displayContent);
        params.add(creator);
        params.add(timeMetric);
        params.add(timeReferenceValue);
        params.add(creator);
        int rows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(rows > 0);
        result.setMessage(rows > 0 ? "Add successful" : "Add failed");
        return result;
    }

    public Result getCurrentUser(Map<String, Object> paramMap) {
        String username = sdkOfGetCurrentUserName();
        Result result = new Result();
        result.setFlag(true);
        result.setMessage("Get current user successful");
        result.setData(username);
        return result;
    }

    public Result updateAlarmRule(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        String timestamp = paramMap.get("Timevalue2") != null ? String.valueOf(paramMap.get("Timevalue2")) : null;
        String projectName = paramMap.get("ProjectName1value2") != null ? String.valueOf(paramMap.get("ProjectName1value2")) : null;
        String deviceName = paramMap.get("EquipmentNamevalue2") != null ? String.valueOf(paramMap.get("EquipmentNamevalue2")) : null;
        String deviceMetric = paramMap.get("Equipmentindexvalue3") != null ? String.valueOf(paramMap.get("Equipmentindexvalue3")) : null;
        String operator = paramMap.get("Operatorvalue2") != null ? String.valueOf(paramMap.get("Operatorvalue2")) : null;
        String targetValue = paramMap.get("TargetValuevalue2") != null ? String.valueOf(paramMap.get("TargetValuevalue2")) : null;
        String unit = paramMap.get("Unitvalue2") != null ? String.valueOf(paramMap.get("Unitvalue2")) : null;
        String category = paramMap.get("Alarmcategoryvalue2") != null ? String.valueOf(paramMap.get("Alarmcategoryvalue2")) : null;
        String displayContent = paramMap.get("Displaycontentsvalue2") != null ? String.valueOf(paramMap.get("Displaycontentsvalue2")) : null;
        String timeMetric = paramMap.get("TimeIndexvalue2") != null ? String.valueOf(paramMap.get("TimeIndexvalue2")) : null;
        String creator = sdkOfGetCurrentUserName();
        String timeReferenceValue = paramMap.get("Timereferencevaluevalue2") != null ? String.valueOf(paramMap.get("Timereferencevaluevalue2")) : null;
        StringBuilder sql = new StringBuilder("UPDATE alarm_rules SET timestamp = ?, project_name = ?, device_name = ?, device_metric = ?, operator = ?, target_value = ?, unit = ?, category = ?, display_content = ?, creator = ?, time_metric = ?, time_reference_value = ?, update_username = ?, update_time = NOW() WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(timestamp);
        params.add(projectName);
        params.add(deviceName);
        params.add(deviceMetric);
        params.add(operator);
        params.add(targetValue);
        params.add(unit);
        params.add(category);
        params.add(displayContent);
        params.add(creator);
        params.add(timeMetric);
        params.add(timeReferenceValue);
        params.add(creator);
        params.add(id);
        int rows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(rows > 0);
        result.setMessage(rows > 0 ? "Update successful" : "Update failed");
        return result;
    }

    public Result deleteAlarmRule(Map<String, Object> paramMap) {
        Integer id = paramMap.get("id") != null ? Integer.valueOf(String.valueOf(paramMap.get("id"))) : null;
        StringBuilder sql = new StringBuilder("DELETE FROM alarm_rules WHERE id = ?");
        List<Object> params = new ArrayList<>();
        params.add(id);
        int rows = executeSQL(sql.toString(), params.toArray());
        Result result = new Result();
        result.setFlag(rows > 0);
        result.setMessage(rows > 0 ? "Delete successful" : "Delete failed");
        return result;
    }
}
